//
//  GroupDetailViewController.m
//  SportSocial
//
//  Created by yull on 15/1/28.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "GroupDetailViewController.h"
#import "ActivityNet.h"
#import "GroupActivity.h"
#import "GroupInfoActivityCell.h"
#import "GroupDetailInfoCell.h"
#import "GroupDetailUserCell.h"
#import "GroupNet.h"
#import "UserModel.h"
#import "GroupTitleCell.h"
#import "GroupUserViewController.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

@interface GroupDetailViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *infoTableView;
@property (nonatomic, strong) NSMutableArray *activityArray;
@property (nonatomic, strong) NSMutableArray *userArray;
@property (nonatomic, strong) NearGroup *groupInfo;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation GroupDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNavibar];
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.infoTableView = [[UITableView alloc] initWithFrame:rect];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    [self.view addSubview:self.infoTableView];
    
    self.infoTableView.tableFooterView = [[UIView alloc] init];
    
    [self loadGroupUser];
    
    [self loadGroupInfo];
    
    [self getActivity];
    
    [self initObserver];
    
    @weakify(self);
    [self.infoTableView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self getActivity];
    }];
}

- (void)initObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive_DeleteGroupMember:) name:@"DeleteGroupMember" object:nil];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    self.navigationItem.title = @"群资料";
    
//    UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightButton1.frame = CGRectMake(0, 0, 50, 26);
//    [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [rightButton1 setTitle:@"退出群" forState:UIControlStateNormal];
//    [rightButton1 addTarget:self action:@selector(onExitGroup:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
//    self.navigationItem.rightBarButtonItem = rightItem1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.groupInfo && self.groupInfo.creator_id == [CurrentUser shareInstance].userId) {
            return 3;
        } else {
            return 2;
        }
    }else {
        return self.activityArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        GroupActivity *activity = [self.activityArray objectAtIndex:indexPath.row];
        
        return [GroupInfoActivityCell calulateCellHeightWithText:activity.content];
    }else {
        
        NSInteger userIndexRow = self.groupInfo.creator_id == [CurrentUser shareInstance].userId ? 1 : 0;
        
        if (indexPath.row == userIndexRow) {
            return [GroupDetailUserCell groupDetailUserCellHeight];
        } else if (indexPath.row == userIndexRow + 1) {
            return [GroupDetailInfoCell calculateCellHeightWithText:self.groupInfo.annou];
        } else {
            return 40.0f;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        NSInteger userIndexRow = self.groupInfo.creator_id == [CurrentUser shareInstance].userId ? 1 : 0;
        
        if (indexPath.row == userIndexRow) {
            GroupDetailUserCell *userCell = [tableView dequeueReusableCellWithIdentifier:@"UserCell"];
            if (!userCell) {
                userCell = [[GroupDetailUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UserCell"];
            }
            [userCell drawCellWithArray:self.userArray];
            return userCell;
        }else if (indexPath.row == userIndexRow + 1) {
            GroupDetailInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:@"InfoCell"];
            if (!infoCell) {
                infoCell = [[GroupDetailInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"InfoCell"];
            }
            [infoCell drawCellWithName:self.groupInfo.name creator:self.groupInfo.creator_name anno:self.groupInfo.annou];
            return infoCell;
        } else {
            GroupTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddUserCell"];
            if (!cell) {
                cell = [[GroupTitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddUserCell"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.textLabel.text = @"添加新成员";
            }
            return cell;
        }
    }else if (indexPath.section == 1) {
        GroupInfoActivityCell *activityCell = [tableView dequeueReusableCellWithIdentifier:@"ActivityCell"];
        if (!activityCell) {
            activityCell = [[GroupInfoActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityCell"];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [activityCell drawCellWithActivity:[self.activityArray objectAtIndex:indexPath.row]];
        return activityCell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        NSInteger userIndexRow = self.groupInfo.creator_id == [CurrentUser shareInstance].userId ? 1 : 0;
        
        if (indexPath.row == userIndexRow) {
            GroupUserViewController *userViewController = [[GroupUserViewController alloc] init];
            userViewController.userArray = self.userArray;
            userViewController.editEnable = userIndexRow == 1;
            userViewController.groudId = self.groupInfo.group_id;
            [self.navigationController pushViewController:userViewController animated:YES];
        } else if (indexPath.row == 0 && userIndexRow != 0) {
            FriendViewController *controller = [[FriendViewController alloc] init];
            controller.fromAddAction = YES;
            controller.groupId = self.groupInfo.group_id;
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

- (void)onExitGroup:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"功能开发中" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

#pragma mark - Notification
- (void)onReceive_DeleteGroupMember:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.infoTableView reloadData];
    });
}

#pragma mark - 网络
- (void)loadGroupUser
{
    if (!self.userArray) {
        self.userArray = [NSMutableArray array];
    }
    
    [GroupNet queryGroupUserWithGroupId:self.groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dictArray = [responseObject objectForKey:@"data"];
            for (NSDictionary *dict in dictArray) {
                [self.userArray addObject:[UserModel userWithDict:dict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.infoTableView reloadData];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)loadGroupInfo
{
    [GroupNet queryGroupWithGroupId:self.groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            self.groupInfo = [NearGroup nearGroupWithDict:[responseObject objectForKey:@"data"]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.infoTableView reloadData];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}
- (void)getActivity
{
    @weakify(self);
    [ActivityNet activityPageWithGroupId:self.groupId pageNumber:self.currentPage+1 pageSize:10 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
            if (dictArray.count > 0) {
                if (!self.activityArray) {
                    self.activityArray = [NSMutableArray array];
                }
                
                self.currentPage = [[[responseObject objectForKey:@"data"] objectForKey:@"pageNumber"] integerValue];
                self.totalPage = [[[responseObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
                
                for (NSDictionary *dict in dictArray) {
                    [self.activityArray addObject:[GroupActivity groupActivityWithDict:dict]];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.currentPage == self.totalPage) {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                    } else {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                    }
                    [self.infoTableView nd_endLoadMore];
                    [self.infoTableView reloadData];
                });
                
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
